•对象的锁标志
–每个对象都有一个锁标志
–使用synchronized可与锁标志交互
•synchronized关键字的用法有两种:
–synchronized语句
–synchronized方法
•synchronized语句:
synchronized (obj){
//在synchronized语句块中
//对obj的成员只能进行同步访问
}
/*• 一旦一个包含同步方法(用synchronized修饰)的线程被CPU调用,其他线程就无法调用相同对象的同步方法。当一个线程在一个同步方法内部,所有试图调用该方法的同实例的其他线程必须等待*/
public class TicketSale implements Runnable {
private volatile int tickets = 50;
public int getTickets() {
return tickets;
}
public void setTickets(int tickets) {
this.tickets = tickets;
}
@Override
public void run() {
while(tickets >0){
saleTicket();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private synchronized void saleTicket() {
if(tickets == 0 ){
return ;
}
System.out.println(Thread.currentThread().getName()+"正在卖出"+tickets--+"张票");
}
}
//Mian方法
package com.neuedu.chaptorHomeWork04;
public class TestMain {
public static void main(String[] args) {
Test1 t1 = new Test1(1,1000);
t1.start();
Test1 t2 = new Test1(1001,2000);
t2.start();
Test1 t3 = new Test1(2001,3000);
t3.start();
}
}